import axios, { AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import router from '@/router/index';
import { ElMessage } from 'element-plus';
import {  useLoading } from '@/store/theme';

const service: AxiosInstance = axios.create({
    timeout: 15000,
    baseURL:  import.meta.env.VITE_API_BASE_URL
});

let whiteApi = ['login']

service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
       let loadingData = useLoading();
        loadingData.setLoading(true); // 开始加载
        if (config.url.includes('agent/upload')) {
            config.headers['Content-Type'] =  'multipart/form-data'
        }
        const token = localStorage.getItem('token');
        whiteApi.forEach((item) => {
            if (!config.url.includes(item)) {
                if (token) {
                    config.headers['token'] = token
                } else {
                    router.replace('/login')
                }
            }
        })
        return config;
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    (response: AxiosResponse) => {
        let loadingData = useLoading();
        loadingData.setLoading(false);
        if (response.status === 200) {
            if (response.data.code != 1) {
                ElMessage.error(response.data.msg);
            }
            return response.data;
        } else {
            Promise.reject();
        }
    },
    (error: AxiosError) => {
        if (error.response.status == 402) {
            localStorage.removeItem('vuems_name');
            localStorage.removeItem('token');
            router.replace('/login')
        }
        return Promise.reject();
    }
);

export default service;
